package pers.vic.boot.console.system.service;

import java.beans.Transient;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import pers.vic.boot.base.service.BaseService;
import pers.vic.boot.console.system.mapper.SysRoleMapper;
import pers.vic.boot.console.system.model.SysMenu;
import pers.vic.boot.console.system.model.SysRole;
import pers.vic.boot.util.collections.CalcDiffCollection;

/**
 * @description:角色表 Service
 * @author Vic.xu
 * @date: 2019-58-29 08:58
 */
@Service
public class SysRoleService extends BaseService<SysRoleMapper, SysRole>{

	/**
	 * 全部菜单:选中当前角色拥有的
	 * @param id
	 * @return
	 */
	public List<SysMenu> roleMenus(Integer id) {
		return mapper.roleMenus(id);
	}

	public static void main(String[] args) {
		List<Integer> curMenuIds = Arrays.asList("3,2,1".split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
		curMenuIds.forEach(System.out::println);
	}
	/**
	 * 保存角色 以及角色关联的菜单
	 * @param entity
	 * @param menuIds
	 */
	@Transient
	public void save(SysRole entity, String menuIds) {
		super.save(entity);
		Integer roleId = entity.getId();
		//保存角色对应的菜单
		if (StringUtils.isNotBlank(menuIds) && menuIds.matches("(\\d|\\d+,|\\d+,\\d+)+")) {
			List<Integer> curMenuIds = Arrays.asList(menuIds.split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
			List<Integer> oldMenuIds = mapper.roleMenuIds(entity.getId());
			//构建两个集合的差别:
			CalcDiffCollection<Integer> calc = CalcDiffCollection.instance(oldMenuIds, curMenuIds);
			
			List<Integer> addMenuIds = calc.getOnlyInNew();
			List<Integer> delMenuIds = calc.getOnlyInOld();
			//新增角色和菜单关联
			if(!addMenuIds.isEmpty()) {
				mapper.addRoleMenu(roleId, addMenuIds);
			}
			//删除角色和菜单关联
			if(!delMenuIds.isEmpty()) {
				mapper.deleteRoleMenu(roleId, delMenuIds);
			}
		} else {
			// 通过角色id删除角色和菜单的关系
			mapper.deleteRoleMenuByRoleId(roleId);
		}
		

	}

	@Override
	protected boolean hasAttachment() {
		return false;
	}

}
